package com.qf.controller;

import com.qf.business.entity.Course;
import com.qf.business.entity.Student;
import com.qf.business.service.ICourseSevice;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Controller
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private ICourseSevice courseSevice;

    @Value("${upload.path}")
    private String uploadPath;

    @RequestMapping("/list")
    public String courseList(Model model){
        List<Course> courses = courseSevice.list();
        model.addAttribute("courses", courses);
        return "courselist";
    }

    /**
     * 课程选择
     * @return
     */
    @RequestMapping("/selector")
    @ResponseBody
    public String selector(Integer cid, @SessionAttribute("login_stu") Student student){
        int result = courseSevice.selectCourse(cid, student.getId());
        return "{\"result\":" + result + "}";
    }


    /**
     * 获取课程封面的图片
     */
    @RequestMapping("/getfengmian")
    public void getCourseFengmian(String fengmian, HttpServletResponse response){

        try (
                InputStream in = new FileInputStream(new File(uploadPath, fengmian));
                OutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
